#include "input.h"


input::input(IDirect3DDevice9 *d3ddev, HWND hWnd)
{
	m_Input = NULL;
	m_hWnd = hWnd;

	if (!(initInput()))
	{
		MessageBox(hWnd,"ERROR in initInput() ","Input failed",MB_OK);
	}
	if (!(initKeyboard(hWnd)))
	{
		MessageBox(hWnd, "ERROR in initKeyboard() ", "Keyboard initialization failed", MB_OK);
	}

	if (!(InitMouse(hWnd)))
	{
		MessageBox(hWnd, "ERROR in InitMouse() ", "Mouse initialization failed", MB_OK);
	}

}

bool input::initInput()
{
	if (FAILED(DirectInput8Create(GetModuleHandle(NULL),DIRECTINPUT_VERSION,IID_IDirectInput8,(void**)&m_Input,NULL)))
	{
		return false;
	}
	return true;
}

bool input::initKeyboard(HWND hWnd)
{
	if (FAILED(m_Input->CreateDevice(GUID_SysKeyboard, &m_KeyInputDev, NULL)))
	{
		return false;
	}
	if (FAILED(m_KeyInputDev->SetDataFormat(&c_dfDIKeyboard)))
	{
		return false;
	}
	if (FAILED(m_KeyInputDev->SetCooperativeLevel(hWnd,DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)))
	{
		return false;
	}
	if (FAILED(m_KeyInputDev->Acquire()))
	{
		return false;
	}
	return true;
}

bool input::InitMouse(HWND hWnd)
{
	DIDEVCAPS MouseCapabilities; 

	if (FAILED(m_Input->CreateDevice(GUID_SysMouse, &m_pDIMouseDevice, NULL)))
	{
		return false;
	}

	if (FAILED(m_pDIMouseDevice->SetDataFormat(&c_dfDIMouse2)))
	{
		return false;
	}

	if (FAILED(m_pDIMouseDevice->SetCooperativeLevel(hWnd, DISCL_BACKGROUND | DISCL_NONEXCLUSIVE)))
	{
		return false;
	}

	if (FAILED(m_pDIMouseDevice->Acquire()))
	{
		return false;
	}

	MouseCapabilities.dwSize = sizeof(MouseCapabilities);
	m_pDIMouseDevice->GetCapabilities(&MouseCapabilities);


	m_dwAxes = MouseCapabilities.dwAxes;
	m_dwButtons = MouseCapabilities.dwButtons;

	return true;
}


bool input::update()
{
	if (FAILED(m_KeyInputDev->GetDeviceState(sizeof(Keybuf),(LPVOID)&Keybuf)))
	{
		return false;
	}

	if (DIERR_INPUTLOST == m_pDIMouseDevice->GetDeviceState(sizeof(m_MouseState),
		(LPVOID)&m_MouseState))
	{
		m_pDIMouseDevice->Acquire();
	}

	POINT pt;
	GetCursorPos(&pt);
	ScreenToClient(m_hWnd, &pt);
	m_x = pt.x;
	m_y = pt.y;
	ShowCursor(false);

	return true;
}

bool input::MouseButtonDown(int Button)
{
	if (m_MouseState.rgbButtons[Button] & 0x80)
	{
		return true;
	}

	return false;
} 

bool input::kpressed(int key)
{
	if (Keybuf[key] & 0x80)
	{
		return true;
	}
	return false;
}


input::~input()
{
	if (m_Input != NULL)
	{
		m_Input->Release();
		m_Input = NULL;
	}

	if (m_KeyInputDev != NULL)
	{
		m_KeyInputDev->Unacquire();
		m_KeyInputDev->Release();
		m_KeyInputDev = NULL;
	}

	if (m_pDIMouseDevice != NULL)
	{
		m_pDIMouseDevice->Unacquire();
		m_pDIMouseDevice->Release();
		m_pDIMouseDevice = NULL;
	}
}
